package general_task;


public abstract class State {
	private int instant;
	private StateStructure structure;
	private int state[];

	State(StateStructure s){
		structure=s;
		state=new int[structure.getStateSize()];
		update();
	}

	State(StateStructure s, int hash){
		structure=s;
		state=new int[structure.getStateSize()];
		rebuildState(hash);
	}

	public void copy(State new_state){
		instant=new_state.instant;
		for(int i=0;i< structure.getStateSize();i++){
			state[i]=new_state.state[i];
		}
	}


	public StateStructure getStructure(){
		return structure;
	}

	public void copySTructure(State s) {
		structure=s.getStructure();
	}


	public void addState(int s[]){
		state=s;
	}

	public int hashCodeSubSet(TruncatedStateStructure ts){
		int code=0;
		for(int i=0;i<ts.getSize();i++){
			Atribute a=structure.getAtribute(ts.getState()[0][i]);
			int value=state[ts.getState()[0][i]];
			code=code*a.getMaxValue(ts.getState()[1][i])+value;
		}
		return code;
	}

	public int hashCode(){
		int code=0;
		for(int i=0;i<structure.getStateSize();i++){
			Atribute a=structure.getAtribute(i);
			int value=state[i];
			code=code*a.getMaxValue(i)+value;
		}
		return code;
	}

	public void rebuildState(int hashCode){
		for(int i=structure.getStateSize()-1;i>=0;i--){
			int div_rem;
			int div_quot;
			Atribute a=structure.getAtribute(i);
			div_quot = hashCode / a.getMaxValue(i);
			div_rem = hashCode % a.getMaxValue(i);
			state[i]=div_rem;
			hashCode=div_quot;
		}
	}

	public void setState(int ind,int value){
		state[ind]=value;
	}

	public void clear(int inst){
		instant=inst;
		for(int i=0;i< structure.getStateSize();i++){
			state[i]=0;
		}
	}

	public void update() {
		instant=structure.getInstant();
		for(int i=0;i< structure.getStateSize();i++){
			state[i]=structure.getAtributeUpdate(i);
		}
		
	}

	@Override
	public String toString() {
		String str="";
		for(int i=0;i<state.length;i++)
			str+=state[i];
		return str;
	}

	public boolean compareAtribute(int i, State new_state) {
		return state[i]==new_state.state[i];
	}
	
}
